import React from 'react';
import { loadable } from '@/components';

export const ConfigContext = React.createContext({});

// 判断是否对象
export const isObject = (value: any) => {
  if ((Object.prototype.toString.call(value) === '[object Object]')) {
    return true
  }
  return false
}

// 判断是否数组
export const isArray = (value: any) => {
  if ((Object.prototype.toString.call(value) === '[object Array]')) {
    return true
  }
  return false
}

// 判断是否字符串
export const isString = (value: any) => {
  if ((Object.prototype.toString.call(value) === '[object String]')) {
    return true
  }
  return false
}

/**
 * 防抖函数
 * @param func 防抖的function
 * @param delay 防抖延迟
 */
export const debounce = (func: Function, delay: number): Function => {
  let timer: any;
  return function (this: any, ...args: any) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
};

/**
 * 节流
 * @param fn 函数
 * @param interval 间隔时间，毫秒
 */
export function throttle(fn: Function, interval: number = 200): Function {
  let flag = false;
  return function (...args: any): void {
    if (!flag) {
      flag = true;
      setTimeout(() => {
        flag = false;
        fn.call(null, ...args); // this 报语法错误，先用 null
      }, interval);
    }
  };
}

// 获取配置组件
export const getComponentConfig = (module: any) => {
  if (isString(module) || (isObject(module) && !module.componentConfig)) {
    return loadable(
      () =>
        Promise.all([
          import(`@/scene/index`),
          import(`@/scene/${module.componentName || module}/index.tsx`),
        ]).then(([index, components]) => {
          return index.default(components.default)
        }).catch(err => {
          console.error(err, 'getComponentConfig');
        })
    )
  } else if (isObject(module)) {
    const name = `scene-${process.env.RENDERER_VITE_ALL_APP_TYPE || 'admin'}-config`
    return loadable(
      () =>
        Promise.all([
          import(`@/scene/index`), // 主文件
          import(`@/scene/${module.componentName}/index.tsx`),
          import(`@/scene-default-config/${module.componentConfig}/config.tsx`), // 默认配置文件
          import(`@/${name}/${module.componentConfig}/config.tsx`),
        ]).then(([index, components, defaultConfig, componentsConfig]) => {
          return index.default(components.default, {
            ...defaultConfig.default,
            ...componentsConfig.default,
          })
        }).catch(err => {
          console.error(err, 'getComponentConfig');
        })
    )
  }
}

// 生成本地预览图
export const getObjectURL = (file: any) => {
  var url: any = null
  if (window.createObjectURL !== undefined) {
    // basic
    url = window.createObjectURL(file)
  } else if (window.URL !== undefined) {
    // mozilla(firefox)
    url = window.URL.createObjectURL(file)
  } else if (window.webkitURL !== undefined) {
    // webkit or chrome
    url = window.webkitURL.createObjectURL(file)
  }
  return url
}

export const versionPathOperation = {
  save: (type, val = '') => {
    const obj = JSON.parse(sessionStorage.getItem('pathObj') || '{}')
    obj[type] = val
    sessionStorage.setItem('pathObj', JSON.stringify(obj))
  },
  get: (type) => {
    const obj = JSON.parse(sessionStorage.getItem('pathObj') || '{}')
    if (type === 'config' && !obj[type]) {
      return window.api.getLocalMirserverPath()
    }
    return obj[type] || ''
  }
}